from django.shortcuts import render
from user.models import AddressInfo
from user.views import user_decoration
from django.http import JsonResponse
from .models import OrderDetailInfo, OrderInfo
from datetime import datetime
from user.models import UserInfo

# 第一个表,购物车表
from cart.models import CartInfo
from goods.models import GoodsInfo
from django.db import transaction  # 开启事物

import time


# Create your views here.


@user_decoration.islogin
# 购物页面提交过后显示的订单页面
def order(request):
    # 地址数据,可以通过uid查到
    uid = request.session.get('uid')
    addrlist = AddressInfo.objects.filter(user_id=uid)

    # 商品列表,需要传递过来,包括商品的数量
    # 其实把购物车单号传过来就好了
    dict = request.GET
    cidlist = dict.getlist('cid')
    cartlist = CartInfo.objects.filter(id__in=cidlist)
    # print(cartlist)


    # 总金额,其实也可以通过传过来,




    context = {'title': '订单', 'addrlist': addrlist,
               'cartlist': cartlist, }
    return render(request, 'order/place_order.html', context)


@transaction.atomic  # 事务
# 定义提交订单的处理页面
@user_decoration.islogin
def order_handle(request):
    # 返回处理结果就可以了
    # 不过需要一些数据来建表
    # 这里还是通过post请求数据,因为要传递数据过来.所以html那边要设置post请求
    # 现在就想,设计什么数据出来.不过先创建好表吧.去models


    #todo 开启事务
    sid = transaction.savepoint()


    dict = request.POST
    # 需要的数据:
    # 用户,总额,地址.创建订单表
    uid = request.session.get('uid')
    # user = UserInfo.objects.get(id=uid)
    total_goods_count = dict.get('total_pay')
    # print(total_goods_count)
    addr = dict['addr']
    # print(addr)
    # # 购物车订单
    cidlist = dict.getlist('cid')
    # for i in cartlist:
    #     print(i)


    # 上面测试的数据是得到了,现在是来分析整个框架.
    # 1 先减去库存,如果库存不够,则后面的都不用执行
    # 2 再删除购物车表
    # 3 生成订单表
    # 4 生成订单详情表


    # open a transaction

    # def viewfunc(request):
    #
    #     a.save()
    #     # transaction now contains a.save()
    #
    #     sid = transaction.savepoint()
    #
    #     b.save()
    #     # transaction now contains a.save() and b.save()
    #
    #     if want_to_keep_b:
    #         transaction.savepoint_commit(sid)
    #         # open transaction still contains a.save() and b.save()
    #     else:
    #         transaction.savepoint_rollback(sid)
    #         # open transaction now contains only a.save()

    # 1 减库存
    # 怎么减?获取商品与数量,去商品订单里面减去库存


    # 生成订单表
    order = OrderInfo()
    forteen = time.strftime('%Y%m%d%H%M%S',time.localtime(time.time()))
    order.oid = '%s%06d' % (forteen, uid)  #这是一个字符串形式
    order.user_id = uid
    order.ototal =  total_goods_count#总额
    order.oaddress = addr  #收货地址
    order.save()
    context = {}
    isok = True
    for cid in cidlist:
        cartinfo = CartInfo.objects.get(id=cid)
        goodinfo = GoodsInfo.objects.get(id=cartinfo.goods_id)
        gkucun = goodinfo.gkucun
        count = cartinfo.count
        # GoodsInfo.objects.get()
        if gkucun > count:
            # 减库存
            goodinfo.gkucun -= count
            goodinfo.save()

            # 生成订单详情表
            orderdetail = OrderDetailInfo()
            orderdetail.goods_id = goodinfo.id
            orderdetail.order_id = order.oid
            orderdetail.price = goodinfo.gprice
            orderdetail.count = cartinfo.count
            orderdetail.save()

            # 再删除购物车表
            # todo 这里不用保存
            cartinfo.delete()

        else:
            isok = False
            break
    context['isok'] = isok
    if isok:
        transaction.savepoint_commit(sid)
    else:
        transaction.savepoint_rollback(sid)

    return JsonResponse(context)
